package e4e;
use strict;
use warnings;
use Dancer ':syntax';
use Dancer::Request;
use Data::Dumper;
use 5.10.1;

#业务包
use evaluation4edu::Admin;

our $VERSION = '0.1';
 
#JSON打解包类
sub enc_json { JSON->new->utf8->pretty->encode(@_) };
sub dec_json { JSON->new->utf8->pretty->decode(@_) };

debug 'initialize ok';

#admin入口
post '/admin' => sub {
	debug '/admin请求';
	#初始化admin
	my $admin = evaluation4edu::Admin->new( config->{database} );

	#解开请求
	debug "请求包体[".request->body."]";
	my $req=dec_json request->body;
	debug "请求函数[$req->{func}] 请求内容:".Dumper $req;

	#处理请求
	my ( $ret,$resp );
	eval {
		( $ret,$resp ) = $admin->sub_call( $req->{func} )->( $admin,$req->{arg} );
	} or do {
		error "错误 msg[$@]";
		return;
	};

	#响应
	debug "响应函数 [$req->{func}] 结果[$ret] 内容[".Dumper($resp)."]";
	my $resp_data;
	eval {
		$resp_data=enc_json {
			ret => $ret,
			data => $resp,
		};
	} or do {
		error "json编码错误 " . Dumper {
			ret => $ret,
			data => $resp
		};
	};

	debug "响应数据[$resp_data]";
	return $resp_data;
};

1;
